import traceback
from bs4 import BeautifulSoup
from crawlers.utils import fetch_webpage
from crawlers.constants import FXBAOGAO_BASE_URL, REQUEST_HEADERS


def get_reports_from_fxbaogao():
    """从发现报告网页中提取报告数据

    Returns:
        日榜，周榜，月榜
        报告数据列表，每个报告包含序号、标题、链接、时间和作者、以及作者链接

    """
    try:
        webpage = fetch_webpage(FXBAOGAO_BASE_URL, REQUEST_HEADERS)
        soup = BeautifulSoup(webpage, "html.parser")
        reports = []
        report_elements = soup.select(
            '[class^="report__app-containers-Fxbaogao-Home-ReportRank-style"] [class^="text-ellipsis"]'
        )

        report_num = len(report_elements) // 3
        for index, element in enumerate(report_elements):
            report_info = {}
            report_info["order"] = (index % report_num) + 1
            link = element.select_one("a")

            if not link:
                continue

            # 提取标题和链接
            report_info["title"] = link.get("title")
            report_info["url"] = f"{FXBAOGAO_BASE_URL}{link.get('href')}"

            # 提取时间和作者信息
            meta_elements = element.select(
                '[class^="metas__app-containers-Fxbaogao-Home-ReportRank-style"] .flex-ca'
            )
            if len(meta_elements) >= 2:
                time_span = meta_elements[0].select_one("span")
                author_link = meta_elements[1].select_one("a")

                if time_span:
                    report_info["created_at"] = time_span.text
                if author_link:
                    report_info["authors"] = []
                    new_author = {}
                    new_author["name"] = author_link.text
                    new_author["url"] = f"{FXBAOGAO_BASE_URL}{author_link.get('href')}"
                    report_info["authors"].append(new_author)

            reports.append(report_info)

        # 日榜
        daily_reports = reports[:report_num]
        # 周榜
        weekly_reports = reports[report_num : report_num * 2]
        # 月榜
        monthly_reports = reports[report_num * 2 : report_num * 3]

        return daily_reports, weekly_reports, monthly_reports
    except Exception as e:
        print("发现报告热榜数据获取失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise
